package adc.budget.impl.hb.bo;

import java.util.SortedSet;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

import adc.budget.spec.bo.ICategory;

import com.google.common.collect.Sets;

@Entity
@Table(name="CATEGORY")
@DiscriminatorValue("CATEGORY")
public class HbCategory extends HbSource implements ICategory {

    private static final long serialVersionUID = 1L;

    private Boolean income;
    private ICategory parent;
    private SortedSet <ICategory> children = Sets.newTreeSet();

    @Override
    @Column(nullable=false)
    public Boolean getIncome() {
        return income;
    }

    @Override
    public void setIncome(Boolean income) {
        this.income = income;
    }

    @Override
    @ManyToOne(targetEntity=HbCategory.class, optional=true)
    public ICategory getParent() {
        return parent;
    }

    @Override
    public void setParent(final ICategory parent) {
        this.parent = parent;
    }

    @Override
    @OneToMany(targetEntity=HbCategory.class, mappedBy="parent")
    @Sort(type=SortType.NATURAL)
    public SortedSet<ICategory> getChildren() {
        return children;
    }

    public void setChildren(final SortedSet<ICategory> children) {
        this.children = children;
    }

    @Override
    public boolean equals(final Object other) {
        if (this == other) {
            return true;
        }
        if (!(other instanceof HbCategory)) {
            return false;
        }
        final ICategory otherCat = (ICategory) other;
        return equals(this.getName(), otherCat.getName());
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(getName()).toHashCode();
    }
}
